<template>
  <view class="template-avatar tn-safe-area-inset-bottom">
    <!-- 顶部自定义导航 -->
    <tn-nav-bar fixed>头像</tn-nav-bar>
    
    <view :style="{paddingTop: vuex_custom_bar_height + 'px'}">
      <view class="cropper-options">
        <!-- <view class="cropper-options__item tn-padding-right-sm" @tap="chooseImage">选择图片</view> -->
        <!-- <view class="cropper-options__item" @tap="saveImagelocal">保存本地</view> -->
      </view>
      
    </view>
    
   <!-- <tn-cropper
      :imageUrl="imageUrl"
      :isRound="isRound"
	  :returnBase64="true"
      @cropper="cropperFinish"
    ></tn-cropper>
    
    <tn-popup
      v-model="showCropperImage"
      :marginTop="vuex_custom_bar_height"
      length="80%"
      mode="center"
      :closeBtn="true"
    >
      <view class="tn-flex tn-flex-col-center tn-flex-row-center" style="margin: 40rpx 60rpx;">
        <image :src="cropperImageUrl" style="width: 80%;" mode="widthFix"></image>
      </view>
    </tn-popup> -->
	<lxiaoxiao-cropper selWidth="660rpx" selHeight="660rpx" @upload="myUpload" :avatarSrc="cropperImageUrl" :loading="tongbuloading" @tongbukaoqin="tongbukaoqin" avatarStyle="width:100vw;height:100vw;"> 
	</lxiaoxiao-cropper>
	
		<tn-toast
		  ref="toast"
		></tn-toast>
  </view>
</template>

<script>
	import lxiaoxiaoCropper from "../../components/lxiaoxiao-cropper/lxiaoxiao-cropper.vue"
  export default {
	  components:{lxiaoxiaoCropper},
    name: 'TemplateAvatar',
    data() {
      return {
        imageUrl: '',
        isRound: true,
        switchText: '切换为正方形裁剪框',
        showCropperImage: false,
        cropperImageUrl: 'https://img1.baidu.com/it/u=946811137,302769443&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1669309200&t=f41038b274ad95001481ff67599c99e2',
		file: null,
		userInfo: {},
		fromPage: '',
		loginType: 1,
		tongbuloading: false,
      }
    },
	onLoad(option) {
		this.fromPage = option.page;
		this.cropperImageUrl = this.config.apiUri + '/sysFileInfo/previewImg?id=' + option.avatarId
		console.log('option ---------- ',option)
	},
	mounted() {
			this.loginType = uni.getStorageSync('loginType');
		this.userInfo = uni.getStorageSync('userInfo');
	},
    methods: {
		compareSetHours(time) {
		  var result = false
		  var times = time.split('-')
		  if (times.length === 2) {
		    var date = new Date()
		    var time1 = times[0].split(':')
		    var time2 = times[1].split(':')
		    result = date.setHours(time1[0], time1[1], time1[2]) < date.setHours(time2[0], time2[1], time2[2])
		  }
		  return result
		},
		tongbukaoqin(options){
			let result = this.compareSetHours('20:00:00-08:00:00')
			if(result){
				this.$refs.toast.show({
						    title: '',
						    content: '20:00-8:00期间机器关闭，无法同步',
						    icon: '',
						    image: '',
						    duration: 2000
				})	
				return
			}
			let postData = {
				userId: '',
				syncDataType: ''
			}
			uni.showLoading({
			    title: '正在同步中...'
			});
			if(this.fromPage == 'baobao'){//学生
				postData = {
					userId: this.userInfo.childId,
					syncDataType: 1
				}
			}else{
				if(this.loginType == 1){//老师
					postData = {
						userId: this.userInfo.userId,
						syncDataType: 2
					}
				}else{//家长
					postData = {
						userId: this.userInfo.userId,
						syncDataType: 3
					}
				}
			}
			this.request({
				url: '/equipment/SingleSyncData',
				method: 'post',
				params: postData
			}).then(res => {
				if(res.code == 200){
					setTimeout(() => {
						this.gettongburesult(res.data)
					},2000)
					
				}else{
					this.$refs.toast.show({
							    title: '',
							    content: res.message || '同步失败',
							    icon: '',
							    image: '',
							    duration: 1000
					})
					uni.hideLoading();
				}
			}).catch(err => {
				
					uni.hideLoading();
			})
		},
		gettongburesult(messageId){
			this.request({
				url: '/equipment/GetSyncCallBack',
				method: 'get',
				params: {
					messageId: messageId
				},
			}).then(res => {
				uni.hideLoading();
				if(res.code == 200){
					if(this.fromPage == 'baobao'){//学生
						this.$refs.toast.show({
								    title: '',
								    content: res.data.clockingInMessage+','+res.data.morningCheckMessage,
								    image: '',
								    duration: 2000
						})
					}else{
						if(this.loginType == 1){//老师
							this.$refs.toast.show({
									    title: '',
									    content: res.data.clockingInMessage,
									    image: '',
									    duration: 2000
							})
						}else{//家长
							this.$refs.toast.show({
									    title: '',
									    content: res.data.clockingInMessage,
									    image: '',
									    duration: 2000
							})
						}
					}
				}
			}).catch(err => {
				uni.hideLoading();
			})
		},
		myUpload(rsp){
			console.log('rsp -------- ',rsp)
			// let file = this.blobToFile(rsp.path)
			// console.log(file)
			// let _blob = this.dataURLtoBlob(rsp.basedata);
			// console.log('---------------',_blob)
			// let file = this.blobToFile(_blob)
			let that = this;
			// console.log(file)
			this.uploadPhoto(rsp.path, rsp.path?rsp.path:'', (resData) => {
						if(resData.code == 200){
							let emitdata = {
								page: this.fromPage,
								imgId: resData.data
							}
							this.cropperImageUrl = this.config.apiUri + '/sysFileInfo/previewImg?id=' + resData.data
							that.$refs.toast.show({
									    title: '',
									    content: '图片保存成功',
									    icon: 'success',
									    image: '',
									    duration: 1000
							})
							uni.$emit('avatarfile', emitdata)
							// uni.navigateBack()
						}
			})
		},
      // 选择图片
      chooseImage() {
        uni.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: ['album','camera'],
          success: (res) => {
			  // console.log(res)
            const tempFilePaths = res.tempFilePaths[0]
            this.imageUrl = tempFilePaths
			// let URL = url.startsWith('file://')
			
          }
        })
      },
	  saveImagelocal(){
		  console.log(this.imageUrl)
		  if(!this.imageUrl){
			  return
		  }
		  uni.saveImageToPhotosAlbum({
		      filePath: this.imageUrl
		  })
	  },
      // 切换裁剪框形状
      switchBorderRect() {
        this.isRound = !this.isRound
        if (this.isRound) {
          this.switchText = '切换为正方形裁剪框'
        } else {
          this.switchText = '切换为圆形裁剪框'
        }
      },
      // 裁剪完成
      cropperFinish(res) {
        // console.log(res);
        // this.showCropperImage = true;
        if (res.url) {
          this.cropperImageUrl = res.url
        }
		console.log(res)
        if (res.base64) {
          this.cropperImageUrl = `${res.base64}`
		  let _name = new Date().getTime() + 'avatar'
			let _blob = this.dataURLtoBlob(res.base64);
			console.log('---------------',_blob)
			let file = this.blobToFile(_blob)
			let that = this;
			console.log(file)
			this.uploadPhoto(file, res.url?res.url:'', (resData) => {
						if(resData.code == 200){
							let emitdata = {
								page: this.fromPage,
								imgId: resData.data
							}
							this.$refs.toast.show({
									    title: '',
									    content: '图片保存成功',
									    icon: 'success',
									    image: '',
									    duration: 1000
							})
							uni.$emit('avatarfile', emitdata)
							// uni.navigateBack()
						}
			})
        }
        
      },
	  
	  // dataURLtoBlob(dataurl, name) {//base64转file
	  //       var arr = dataurl.split(','),
	  //         mime = arr[0].match(/:(.*?);/)[1],
	  //         bstr = atob(arr[1]),
	  //         n = bstr.length,
	  //         u8arr = new Uint8Array(n)
	  //       while (n--) {
	  //         u8arr[n] = bstr.charCodeAt(n)
	  //       }
	  //       return new File([u8arr], name, {
	  //         type: mime,
	  //       })
	  // },
	  dataURLtoBlob(dataurl) {
	        var arr = dataurl.split(',');
	        var  mime = arr[0].match(/:(.*?);/)[1];
	        var  bstr = atob(arr[1]);
	        var  n = bstr.length;
	        var  u8arr = new Uint8Array(n);
	        while (n--) {
	          u8arr[n] = bstr.charCodeAt(n);
	        }
	        return new Blob([u8arr], { type: mime });
	      },
	      //2,再将blob转换为file
	      blobToFile(theBlob, fileName){
	         theBlob.lastModifiedDate = new Date();  // 文件最后的修改日期
	         theBlob.name = fileName;                // 文件名
	         return new File([theBlob], fileName, {type: theBlob.type, lastModified: Date.now()});
	      },
	  
	  uploadPhoto(file, filePath,callBack){
	  	uni.uploadFile({
	  	    url: this.config.apiUri + '/sysFileInfo/UploadFileInfo',
	  		// files: arr,
	  		name: 'file',
	  		file: file,
	  		filePath: filePath,
	  	    header: {
	  			'Authorization': 'Bearer '+ uni.getStorageSync('token')
	  	    },
	  	    success: (res) => {
	  			let resData = JSON.parse(res.data)
	  			if(resData.code == 200){
	  				if(callBack){
	  					callBack(resData);
	  				}
	  			}else{
	  				  this.$refs.toast.show({
	  				    title: '',
	  				    content: resData.message || '错误',
	  				    icon: 'fail',
	  				    image: '',
	  				    duration: 1500
	  				  })
	  			}
	  	    },
	  		fail:(err) => {
	  			console.log(err)
	  		}
	  	});
	  },
    }
  }
</script>

<style lang="scss" scoped>
	.template-avatar{
		height: 100vh;
		background-color: #000000;
	}
  .cropper-options {
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    margin-top: 90rpx;
    
    &__item {
      color: #FFFFFF;
      font-size: 28rpx;
      padding: 18rpx 56rpx;
      border: 2rpx solid #FFFFFF;
      z-index: 1000;
      
      &:nth-child(1) {
        // border-right: none;
      }
    }
  }
</style>
